<template>
  <view>
    <view class="cart-settle">
      
      <view class="left">
        <radio @click="updateFullCheck(!fullCheck)" :checked="fullCheck"  color="#C00000"></radio>
        <text class="selected">全选</text>
      </view>
      
        <view class="amount-box">合计： 
          <text class="amount" >¥ {{totalPrice}}</text>
        </view>
      
        <view class="btn-settle" @click="settlement">结算：({{checkedCount}})</view>
    </view>
  </view>
</template>

<script>
  import {mapGetters, mapMutations, mapState} from 'vuex'
  export default {
    name:"my-settle",
    data() {
      return {
        //倒计时秒数
        scends: 3,
        timer: null,
      }
    },
    computed: {
      ...mapState('cart', ['cart']),
      ...mapGetters('cart', ['checkedCount', 'total', 'totalPrice']),
      ...mapGetters('user', ['addstr', 'token']),
      fullCheck () {
        return this.checkedCount === this.total
      }
    },
    methods: {
      ...mapMutations('cart', ['updateAllCheck']),
      ...mapMutations('user', ['updateRedirectinfo']),
      updateFullCheck(c) {
        this.updateAllCheck(c)
      },
      //点击结算
      settlement() {
        //判断商品是否选中
        if(!this.checkedCount) return uni.$showMsg('请选择要结算的商品')
        //判断是否选择了地址
        if(!this.addstr) return uni.$showMsg('请选择收获地址')
        //判断是否登录,未登录，弹出跳转到登录页的倒计时信息
        if(this.token) {
          //已登录实现支付功能
          this.payMent()
        } else {
          //未登录，跳转到登录页登录
          this.delayNavigate()
          } 
      },
      //支付
      async payMent() {
        //创建订单，拿到订单编号
        //参数对象
        let query = {
          order_price: 0.1,
          consignee_addr: this.addstr,
          goods: this.cart.filter(x => x.goods_state).map(x => ({
            goods_id: x.goods_id,
            goods_number: x.goods_count,
            goods_price: x.goods_price
          }))
        }
        //发请求
        const {data: res} = await uni.$http.post('/api/public/v1/my/orders/create', query)
        if(res.meta.status !== 200) return uni.$showMsg('创建订单失败')
        //创建成功得到信息
        const orderNumber = res.message.order_number
        //订单创建成功，进行预支付支付，携带订单编号，获取订单的支付信息
        const {data: res1} = await uni.$http.post('/api/public/v1/my/orders/req_unifiedorder', {order_number: orderNumber})
        if(res1.meta.status !== 200) return uni.$showMsg('预付订单生成失败')
        //预付订单生成成功后，获取信息
        const payinfo = res2.message.pay
        
        //进行支付，调用API
        const [err, succ] = await uni.requestPayment(payinfo)
        //订单支付失败
        if(err) return uni.$showMsg('订单支付失败')
        //订单支付成功，查询订单支付状态
        const {data: res3} = await uni.$http.post('/api/public/v1/my/orders/chkOrder', {order_number: orderNumber})
        if(res3.meta.status !== 200) return uni.$showMsg('订单未支付')
        uni.showToast({
          icon: 'success',
          title: '订单支付完成'
        })
        
        
        
      },
      // 弹出跳转到登录页的倒计时信息: 
      delayNavigate() {
        // 把 data 中的秒数重置成 3 秒
        this.scends = 3
        this.tipInfo(this.scends)
        //定时器
        this.timer = setInterval(() => {
          this.scends--
          if(this.scends <= 0) {
            //清除定时器
            clearInterval(this.timer)
            //跳转到登录页
            uni.switchTab({
              url: '/pages/my/my',
              success: () => {
                // 调用 vuex 的 updateRedirectInfo 方法，把跳转信息存储到 Store 中
                this.updateRedirectinfo({
                  // 跳转的方式
                   openType: 'switchTab',
                   // 从哪个页面跳转过去的
                  from: '/pages/cart/cart'
                })
              }
            })
            return
          }
          //根据最新的秒数，进行消息提示
          this.tipInfo(this.scends)
        }, 1000)
        
      },
      //提示信息
      tipInfo(n) {
        // 调用 uni.showToast() 方法，展示提示消息
        uni.showToast({
          icon: 'none',
          title: '请登录后再结算' + n + '秒后自动跳转到登录页',
          // 为页面添加透明遮罩，防止点击穿透
          mask: true,
          //1.5秒后自动消失
          duration: 1500
        })
      }
    },
    //过滤器， 保留两位小数
    filters: {
      //把数字处理为带两位小数的数字
      toFixed(num) {
        return Number(num).toFixed(2)
      }
    }
  }
</script>

<style lang="scss">
  .cart-settle {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-left: 5px;
    .left {
      display: flex;
      align-items: center;
    }
    .amount-box {
      .amount {
        color: #C00000;
        font-weight: bold;
      }
    }
    .btn-settle {
      background-color: #C00000;
      line-height: 50px;
      color: white;
      height: 50px;
      padding: 0 10px;
      min-width: 100px;
      text-align: center;
    }
  }
</style>